package com.aftersale.platform.controller;

import com.aftersale.platform.dto.ApiResponse;
import com.aftersale.platform.entity.Announcement;
import com.aftersale.platform.service.AnnouncementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/announcements")
public class AnnouncementController {

    @Autowired
    private AnnouncementService announcementService;

    @GetMapping
    public ResponseEntity<ApiResponse<List<Announcement>>> getAllAnnouncements() {
        List<Announcement> announcements = announcementService.findAll();
        return ResponseEntity.ok(ApiResponse.success(announcements, "获取公告成功"));
    }

    @PostMapping
    public ResponseEntity<ApiResponse<Announcement>> addAnnouncement(@RequestBody Announcement announcement) {
        // 简单验证
        if (announcement.getTitle() == null || announcement.getTitle().trim().isEmpty() ||
                announcement.getContent() == null || announcement.getContent().trim().isEmpty()) {
            return ResponseEntity.badRequest().body(ApiResponse.error("标题和内容不能为空！"));
        }
        announcementService.save(announcement);
        return ResponseEntity.ok(ApiResponse.success(announcement, "公告发布成功！"));
    }

    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Announcement>> updateAnnouncement(@PathVariable Integer id, @RequestBody Announcement announcement) {
        Announcement existing = announcementService.findById(id);
        if (existing == null) {
            return ResponseEntity.notFound().build();
        }
        existing.setTitle(announcement.getTitle());
        existing.setContent(announcement.getContent());
        announcementService.update(existing);
        return ResponseEntity.ok(ApiResponse.success(existing, "公告更新成功！"));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteAnnouncement(@PathVariable Integer id) {
        announcementService.delete(id);
        return ResponseEntity.ok(ApiResponse.success(null, "公告删除成功！"));
    }
}